package com.sdry.web.controller.jyy.test;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Controller;

import com.sdry.model.jyy.Temp;
import com.sdry.service.jyy.TempServise;

/**
 * @ClassName:    [SerialComm4MainWindows]   
 * @Description:  [串口测试]   
 * @Author:       [jyy]   
 * @CreateDate:   [2018年12月24日 上午10:24:52]    
 * @Version:      [v1.0]
 */
@Controller
public class SerialComm implements ApplicationListener<ContextRefreshedEvent> {
	
	@Resource
	private TempServise tempServise;
	
	private static final Log LOGGER = LogFactory.getLog(SerialComm.class);
	
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		try {
			if (event.getApplicationContext().getParent() == null) {
				// 需要实现的功能
				System.out.println("组件评价监听器启动。。。。");
				try {
					/*connect("COM5");*/

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			LOGGER.error("StartGateServiceData", e);
		}
	}

	private static SerialPort serialPort;

	/**
	 * 链接硬件
	 * @param portName 串口名称
	 * @throws Exception
	 */
	public void connect(String portName) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
		if (portIdentifier.isCurrentlyOwned()) {
			System.out.println("Error: Port is currently in use");
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
			if (commPort instanceof SerialPort) {
				serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

				InputStream in = serialPort.getInputStream();
				
				(new Thread(new SerialReader(in))).start();
				
				byte[] buffer = new byte[1024];
				System.out.println("============="+in.read(buffer));
			} else {
				System.out.println("Error: Only serial ports are handled by this example.");
			}
		}
	}


	/** 读串口数据*/
	public class SerialReader implements Runnable {
		InputStream in;
		public SerialReader(InputStream in) {
			this.in = in;
		}
		public void run() {
			
			List<String> list = new ArrayList<String>();
			Temp temp = new Temp();
			byte[] buffer = new byte[1024];
			int len = -1;
			try {
				while ((len = this.in.read(buffer)) > -1) {
					String getValue = new String(buffer, 0, len);
					if(getValue != null && getValue != "" && getValue.length() > 2) {
						System.out.println(getValue);
						
						String[] split = getValue.split(",");

						if(split.length >= 10) {
							for (String s : split) {
								String[] split2 = s.split(":");
								if(split2.length >= 2) {
									list.add(split2[1]);
								}
							}
							
							if(list.size() >= 10) {
								temp.setNumber(list.get(0));
								temp.setTemperature(list.get(1));
								temp.setEnter(list.get(2));
								temp.setBring(list.get(3));
								temp.setThick(list.get(4));
								temp.setThrough(list.get(5));
								temp.setThrough2(list.get(6));
								temp.setThrough3(list.get(7));
								temp.setThrough4(list.get(8));
								temp.setTimelong(list.get(9));
								temp.setResult(list.get(10));
								
								//插入前先查询该机器的数据是否已有，已有删除后插入，没有直接插入
								int count = tempServise.countByNumber(list.get(0));
								
								if(count > 0) {
									tempServise.delete(list.get(0));
								}
								//插入
								tempServise.insert(temp);
								
								OutputStream outputStream = serialPort.getOutputStream();
								outputStream.write(("已成功接收").getBytes("GB2312"));
								outputStream.close();
							}
						}else {
							OutputStream outputStream = serialPort.getOutputStream();
							outputStream.write(("对不起，数据格式异常").getBytes("GB2312"));
							outputStream.close();
						}
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args)  {
		try {
			(new SerialComm()).connect("COM5");
			 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
